<template>
  <div class="person-form-page">
    <a-breadcrumb>
      <a-breadcrumb-item>
        <router-link to="/home">首页</router-link>
      </a-breadcrumb-item>
      <a-breadcrumb-item><router-link to="/person/person">人员管理</router-link></a-breadcrumb-item>
      <a-breadcrumb-item>人员信息</a-breadcrumb-item>
    </a-breadcrumb>
    <a-card>
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <input type="hidden" v-model="formState.id" name="id"/>
        <a-form-item ref="name" label="姓名" name="name">
          <a-input v-model:value="formState.name" name="name" :maxlength="15" allow-clear/>
        </a-form-item>
        <a-form-item ref="username" label="登录账号" name="username">
          <a-input v-model:value="formState.username" name="username" :maxlength="20" allow-clear/>
        </a-form-item>
        <a-form-item ref="password" label="登录密码" name="password">
          <a-input v-model:value="formState.password" name="password" :maxlength="20" allow-clear/>
        </a-form-item>
        <a-form-item ref="phone" label="联系电话" name="phone">
          <a-input v-model:value="formState.phone" name="phone" :maxlength="20" allow-clear/>
        </a-form-item>
        <a-form-item ref="teamName" label="所属班组" name="teamName">
          <a-input v-model:value="formState.teamName" name="teamName" readonly @click="openTeamModal" allow-clear>
            <template #addonAfter>
              <team-modal @onSelectedTeam="onSelectedTeam" ref="teamModal"></team-modal>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item ref="remark" label="备注" name="remark">
          <a-textarea :rows="4" name="remark" v-model:value="formState.remark" show-count :maxlength="200" allow-clear/>
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button type="primary" @click="onSubmit">保存</a-button>
          <a-button style="margin-left: 10px" @click="goback">返回</a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script lang="ts">
import { RuleObject, ValidateErrorEntity } from 'ant-design-vue/es/form/interface'
import { defineComponent, reactive, ref, UnwrapRef, watch } from 'vue'
import { PersonModel } from './js/person-model'
import TeamModal from '../biz-common/team-modal.vue'
import { TeamModel } from '../team/js/team-model'
import { PersonApi } from '@/views/person/js/person-api'
import { ResultModel } from '@/common/result.model'
import { message } from 'ant-design-vue'
import { CommonUtils } from '@/common/common-utils'
import { TeamApi } from '@/views/team/js/team-api'
import { useRouter } from 'vue-router'
import $store from '@/store'

export default defineComponent({
  components: {
    TeamModal
  },
  data () {
    const validateUsername = async (rule: RuleObject, value: string) => {
      const regex = /^[0-9 | a-z | A-Z | \\_\\@\\.]+$/g
      if (!regex.test(value)) {
        // eslint-disable-next-line prefer-promise-reject-errors
        return Promise.reject('只能输入字母、数字、下划线(_)、点(.)、艾特(@)')
      }
    }
    const validatePhone = async (rule: RuleObject, value: string) => {
      const regex = /^1(3[0-9]|4[5,7]|5[0,1,2,3,5,6,7,8,9]|6[2,5,6,7]|7[0,1,7,8]|8[0-9]|9[1,8,9])\d{8}$/
      if (!CommonUtils.isNullValue(value) && !regex.test(value)) {
        console.log(value)
        // eslint-disable-next-line prefer-promise-reject-errors
        return Promise.reject('手机号格式有误！')
      }
    }
    const validateUsernameExit = (rule: RuleObject, value: string, callback: any) => {
      // @ts-ignore
      const formValueStr = JSON.stringify(this.formState)
      const id = JSON.parse(formValueStr).id
      if (value !== '') {
        PersonApi.findByUsername(value)
          .then((response: ResultModel) => {
            if (ResultModel.isSuccess(response) && response.data && response.data.id !== id) {
              return Promise.reject(new Error('此用户名已存在'))
            } else {
              callback()
            }
          })
          .catch(e => callback(new Error(e.message)))
      }
    }
    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      rules: {
        name: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 15,
            message: '姓名应为2-15个文字',
            trigger: 'change'
          }
        ],
        username: [
          {
            min: 6,
            max: 20,
            message: '登录账号应为6-20个文字',
            trigger: 'change'
          },
          {
            validator: validateUsername,
            trigger: 'blur'
          },
          {
            validator: validateUsernameExit,
            trigger: 'blur'
          }
        ],
        phone: [
          {
            validator: validatePhone,
            trigger: 'blur'
          }
        ],
        teamName: [
          {
            required: true,
            message: '请选择所属小组',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  mounted () {
    const id:string = this.$route.params.id as string
    if (id) {
      PersonApi.get(id).then(response => {
        const team = response.data
        Object.assign(this.formState, team)
      })
    } else {
      TeamApi.count().then(response => {
        if (ResultModel.isSuccess(response) && response.data === 0) {
          message.success('请先创建班组信息')
          this.$router.push('/team/team/form')
        }
      })
    }
  },
  methods: {
    goback () {
      this.$router.push('/person/person')
    },
    openTeamModal () {
      console.log('openTeamModal()')
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      this.$refs.teamModal && this.$refs.teamModal.showTeamModal()
    },
    onSelectedTeam (team: TeamModel) {
      console.log(team)
      this.formState.teamName = team.name
      this.formState.teamId = team.id
    }
  },
  setup () {
    const loginUser = ref($store.state.loginUser)
    const $router = useRouter()
    const formRef = ref()
    const formState: UnwrapRef<PersonModel> = reactive({
      name: ''
    })
    const value = ref<string>()
    watch(value, () => {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      console.log(value.value)
    })
    const onSubmit = () => {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      formRef.value
        .validate()
        .then(() => {
          PersonApi.save(formState).then(response => {
            if (ResultModel.isSuccess(response)) {
              message.success('保存成功！')
              // eslint-disable-next-line @typescript-eslint/ban-ts-comment
              // @ts-ignore
              if (loginUser.value?.id === response.data.id) {
                console.log('修改后的用户信息：', response.data)
                $store.commit('updateLoginUser', response.data)
              }
              $router.push('/person/person/form/success?id=' + response.data.id)
            }
          })
        })
        .catch((error: ValidateErrorEntity<PersonModel>) => {
          console.log('error', error)
        })
    }
    const resetForm = () => {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      formRef.value.resetFields()
    }
    return {
      formState,
      formRef,
      value,
      onSubmit,
      resetForm
    }
  }
})
</script>

<style scoped>
.ant-input-group-addon{
  padding:0!important
}
.ant-input-group-addon div{
  padding: 0 11px;
  cursor: pointer;
}
</style>
